package com.shark.uh.service.impl;

import com.shark.uh.enums.ResponseCode;
import com.shark.uh.exception.BusinessException;
import com.shark.uh.service.RedisService;
import com.shark.uh.service.VerificationCodeService;
import com.shark.uh.utils.Generator;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class EmailVerificationCodeServiceImpl implements VerificationCodeService {

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private MailProperties mailProperties;

    @Resource
    private RedisService redisService;

    /**
     * 发送验证码
     *
     * @param target 发送目标方
     */
    @Override
    public void send(String target) {

        // 生成验证码
        String verificationCode = Generator.generateCaptcha();

        // 发送验证码到邮箱
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailProperties.getUsername());
        message.setTo(target);
        message.setSubject("验证码");
        message.setText(verificationCode);
        mailSender.send(message);

        // 将验证码存入redis
        redisService.saveToRedisMinute(target, verificationCode, 10);
    }

    /**
     * 校验验证码
     *
     * @param target 发送目标放
     * @param code   验证码
     */
    @Override
    public void verify(String target, String code) {
        String codeCache = redisService.getString(target);
        if (codeCache == null) {
            throw new BusinessException(ResponseCode.CAPTCHA_EXPIRED);
        }
        if (!code.equals(codeCache)) {
            throw new BusinessException(ResponseCode.PASSWORD_WRONG);
        }
        redisService.del(target);
    }


}
